package com.jyxd.web.service.assessment.basic;

import cn.hutool.core.collection.CollectionUtil;
import com.jyxd.web.data.basic.BedBindDevice;
import com.jyxd.web.data.mongo.BreathProperty;
import com.jyxd.web.data.patient.Patient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Sorts;
import org.apache.commons.lang3.StringUtils;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class MongodbService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IBedBindDeviceService bedBindDeviceService;

    public static final int INTERVAL_MIN = 3;

    public BreathProperty getBreathProperty(Patient patient, Date dataTime, String tenantId) {
        String bedCode = patient.getBedCode();
        if(StringUtils.isBlank(bedCode)){
            return null;
        }

        //根据床位id、租户id获取呼吸机 id
        BedBindDevice bedBindDevice = bedBindDeviceService.selectOneByBedCodeAndTenantId(bedCode,tenantId,dataTime);
        if(Objects.isNull(bedBindDevice) || StringUtils.isBlank(bedBindDevice.getDeviceId())){
            return null;
        }

        String deviceId = bedBindDevice.getDeviceId();
        Long startTime = dataTime.getTime() + INTERVAL_MIN * 60 * 1000;
        Long endTime = dataTime.getTime();
        Query query = new Query();
        query.addCriteria(Criteria.where("deviceId").is(deviceId).and("dataTime").gte(startTime).and("dataTime").lte(endTime));
        query.with(Sort.by("dataTime").descending()).limit(1);
        return mongoTemplate.findOne(new Query(), BreathProperty.class);
    }

    public Document getMonitorData(String deviceId, Long startTime, Long endTime) {
        MongoCollection<Document> collection = mongoTemplate.getDb().getCollection("monitor_data");
        Bson bson = Filters.and(Arrays.asList(
                Filters.eq("deviceId", deviceId),
                Filters.gte("timestamp", startTime),
                Filters.lte("timestamp", endTime)
        ));

        Bson sort = Sorts.descending("timestamp");
        FindIterable<Document> iterable = collection.find(bson).sort(sort).limit(1);

        List<Document> list = new ArrayList<>();
        iterable.forEach(document -> {
            list.add(document);
        });
        if (CollectionUtil.isEmpty(list)) {
            return null;
        }
        return list.get(0);
    }
}
